<template>
  <div>
    <el-upload
      class="upload-demo"
      :action="uploadUrl"
      :data="formData"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :on-success="successIcon"
      :on-error="errorIcon"
      :limit="1"
      :on-exceed="handleExceed"
      :file-list="fileList"
      accept=".jpg,.jpeg,.png,.gif,.bmp,.pdf,.JPG,.JPEG,.PBG,.GIF,.BMP,.PDF"
    >
      <el-button size="small" type="primary" @click="uploadOss" v-if="fileList.length == 0"
        >点击上传</el-button
      >
        <div slot="tip" class="el-upload__tip">只能上传一张图片</div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" append-to-body width="30%">
      <img :src="showImgUrl" style="width: 100%; heighr: 200px" />
    </el-dialog>
  </div>
</template>
<script>
import {
  getImgOssProduct,
  addImgOssProduct,
  deleteImgProduct,
} from "../../../src/assets/js/api";
export default {
  name: "ProductIcon",
  props: ["iconId", "iconUrl"],
  data() {
    return {
      fileList: [],
      uploadUrl: "",
      formData: {},
      dialogVisible: false,
      showImgUrl: "",
    };
  },
  created() {
    if (this.iconUrl.name && this.iconUrl.url) {
      this.fileList.push(this.iconUrl);
    }
  },
  methods: {
    // 获取oss数据
    uploadOss() {
      getImgOssProduct().then((res) => {
        let dataOss = res.data;
        this.formData.key = dataOss.dir + dataOss.fileName + ".png";
        this.formData.OSSAccessKeyId = dataOss.accessid;
        this.formData.policy = dataOss.policy;
        this.formData.Signature = dataOss.signature;
        this.formData.success_action_status = 200;
        this.uploadUrl = dataOss.host;
        this.fileName = dataOss.fileName;
      });
    },
    successIcon() {
      let data = {};
      data.productShowName = this.fileName + ".png";
      data.id = this.iconId;
      addImgOssProduct(data).then((res) => {
        this.$emit("IconClose", false);
        this.fileList = [];
        if (res.code == 200) {
          this.$message.success(res.message);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    errorIcon() {
      this.$message.error("上传失败");
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePreview(file) {
      this.showImgUrl = file.url;
      this.dialogVisible = true;
    },
    handleExceed(files, fileList) {
      console.log(files, fileList);
    },
    beforeRemove(file, fileList) {
      deleteImgProduct(this.iconId).then((res) => {
        this.$emit("IconClose", false);
        this.fileList = [];
        if (res.code == 200) {
          this.$message.success(res.message);
        } else {
          this.$message.error(res.message);
        }
      });
      console.log(file, fileList);
      // return this.$confirm(`确定移除 ${file.name}？`);
    },
  },
};
</script>
<style scoped type="less">
</style>